package com.itheima.reggie.controller;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.UserDto;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R Send(@RequestBody UserDto userDto, HttpSession session){
        String phone = userDto.getPhone();
        if(StringUtils.isEmpty(phone)){
            return R.error("当前没有输入手机号");
        }else{
            String code = RandomUtil.randomNumbers(6);
            userDto.setCode(code);
            //AliyunSmsUtil.sendSms(phone,code);
            //session.setAttribute(phone,code);
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            log.info(code);
            return R.success(userDto);
        }
    }




    @PostMapping("/login")
    public R login(@RequestBody Map map,HttpSession session){
        String phone =  map.get("phone").toString();
        String code =  map.get("code").toString();
        //String CodeStr =  session.getAttribute(phone).toString();
        Object CodeStr = redisTemplate.opsForValue().get(phone);
        session.removeAttribute(phone);
        if(StringUtils.isEmpty(phone)|| StringUtils.isEmpty(code)){
            return R.error("当前验证码或手机号没输入,登录失败!");
        }
        if(code.equals(CodeStr)){
            //判断当前登录的用户是否是新用户
            User user = new User();
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(true,User::getPhone,phone);
            User one = userService.getOne(queryWrapper);
            if(one==null){
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("loginUser",one);
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登录失败");
    }




    @PostMapping("/loginout")
    public R loginout(HttpSession session){
        session.removeAttribute("loginUser");
        return R.success("退出成功");

    }
}
